package com.pj.wisdomlogistics.ui.view;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.pj.wisdomlogistics.R;


public class CustomLoadingDialog implements View.OnClickListener{
    private View mRootView;
    private Context mContext;
    private LoadingView mLoadingView;
    private boolean isCancel;
    private final int HIDE_VALUE = 2;
    private int mHideValue;
    private FrameLayout mWindow;
    private FrameLayout.LayoutParams mWParams;

    private CustomLoadingDialog(Context context)
    {
        mContext = context;
    }

    public static CustomLoadingDialog Builder(Context context){
        return new CustomLoadingDialog(context);
    }

    private void initView()
    {
        mRootView = LayoutInflater.from(mContext).inflate(R.layout.load_layout,null);
        mLoadingView= (LoadingView) mRootView.findViewById(R.id.mv_loading);
        mRootView.setOnClickListener(this);
        mWindow = (FrameLayout)((Activity)mContext).getWindow().getDecorView();

        mWParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mWParams.gravity = Gravity.CENTER;
        mRootView.setLayoutParams(mWParams);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run()
            {
                hide();
                mHideValue += 1;
            }
        },1000);
    }

    private void removeViewWithAnimation(){
        if (mRootView != null){
            removeViewImmediate();
        }
    }

    public void removeViewImmediate(){
        if(mRootView != null && mRootView.getParent() != null)
        {
            mWindow.removeView(mRootView);
        }
    }


    public void hide()
    {
        mHideValue +=1;
        if (mHideValue >= HIDE_VALUE){
            mHideValue = 0;
            isCancel = false;
            removeViewWithAnimation();
        }
    }

    public void show()
    {
        initView();
        mWindow.addView(mRootView);
    }

    public void show(boolean isCancel)
    {
        this.isCancel = isCancel;
        show();
    }

    @Override
    public void onClick(View v)
    {
        if(isCancel)
        {
            hide();
        }
    }
}